<template>
  <Card>
    <Row>
      <Col>
        <Button @click="newRule" style="float:right;margin-right:10px;margin-bottom:10px;" type="primary">新建规则</Button>
      </Col>
    </Row>
    <Table :columns="columns1" :data="pageDataRule.list"></Table>
    <br>
    <div style="text-align:center;">
      <Page :total="pageDataRule.total" :current="pageDataRule.pageNum" :page-size="pageDataRule.pageSize" show-elevator show-total @on-change="changePage"></Page>
    </div>
    <Modal
        v-model="modalRule"
        :title="operateType=='new'?'新建规则':'规则详情'"
        :mask-closable="false"
        :footer-hide="operateType=='view'"
        @on-ok="handleOk"
        @on-cancel="handleCancel"
        @on-visible-change="modalRuleVisibleChange"
        width="900">
      <Row type="flex" align="middle" :gutter="8">
        <Col span="2">
          产品类型：
        </Col>
        <Col span="6">
          <Select v-model="ruleConfig.productOverdueCfg.patternCode" @on-change="changePattern" label-in-value>
            <Option v-for="item in selectDataPattern" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="2">
          逾期类型：
        </Col>
        <Col span="6">
          <Select v-model="ruleConfig.productOverdueCfg.overdueTypeCode" @on-change="changeOverdueType" label-in-value>
            <Option v-for="item in selectDataOverdueTypes" :value="item.overdueTypeCode" :key="item.overdueTypeCode">{{ item.overdueTypeName }}</Option>
          </Select>
        </Col>
      </Row>
      <br>
      <Row type="flex" align="middle" :gutter="8">
        <Col span="2">
          规则描述：
        </Col>
        <Col span="14">
          <Input v-model="ruleConfig.productOverdueCfg.remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入内容"></Input>
        </Col>
      </Row>
      <br>
      <Table :columns="columns2" :data="collectorConfigList"></Table>
    </Modal>
  </Card>
</template>

<script>
export default {
  data () {
    return {
      $ajax: null,
      baseUrl: null,
      columns1: [
        {
          align: 'center',
          type: 'index',
          width: 60,
          title: '序号'
        },
        {
          align: 'center',
          title: '产品类型',
          key: 'patternName'
        },
        {
          align: 'center',
          title: '逾期类型',
          key: 'overdueTypeName'
        },
        {
          align: 'center',
          title: '规则描述',
          key: 'remark'
        },
        {
          align: 'center',
          title: '状态',
          key: 'validFlag',
          render: function (h, params) {
            let validFlag = params.row.validFlag + ''
            return h('span', {
              style: {
                color: 'blue'
              }
            }, this.ruleStatus[validFlag])
          }.bind(this)
        },
        {
          align: 'center',
          title: '创建时间',
          key: 'createdDate',
          render: function (h, params) {
            let time = this.$util.formatTime(params.row.createdDate)
            return h('span', {}, time)
          }.bind(this)
        },
        {
          align: 'center',
          title: '创建人',
          key: 'createdBy'
        },
        {
          align: 'center',
          title: '更新时间',
          key: 'updatedDate',
          render: function (h, params) {
            let time = this.$util.formatTime(params.row.updatedDate)
            return h('span', {}, time)
          }.bind(this)
        },
        {
          align: 'center',
          title: '操作人',
          key: 'updatedBy'
        },
        {
          align: 'center',
          title: '操作',
          key: 'action',
          // width: 200,
          render: function (h, params) {
            var vm = this
            let aryBtn = [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    vm.showRuleConfigDetail(params.row.id)
                  }
                }
              }, '查看')
            ]
            if (params.row.validFlag === 0) {
              aryBtn.push(
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      vm.updateConfigValid(params.row, 1)
                    }
                  }
                }, '失效')
              )
            } else {
              aryBtn.push(
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      vm.updateConfigValid(params.row, 0)
                    }
                  }
                }, '生效')
              )
            }
            return h('div', {}, aryBtn)
          }.bind(this)
        }
      ],
      pageDataRule: {
        list: [],
        pageNum: 1,
        pageSize: 10,
        total: 0,
        pages: 1
      },
      modalRule: false,
      selectDataPattern: [
        {
          value: 'A',
          label: '线上产品'
        },
        {
          value: 'B',
          label: '线下产品'
        }
      ],
      ruleStatus: {
        '0': '有效',
        '1': '无效'
      },
      selectDataOverdueTypes: [], // 逾期类型下拉列表
      selectDataOverdueTags: [], // 逾期标签配置列表
      collectors: [], // 催收人员
      ruleConfig: {}, // 一个规则配置详情
      newRuleConfigTempData: {// 新建规则时的规则数据结构
        productOverdueCfg: {
          patternCode: null,
          patternName: null,
          overdueTypeCode: null,
          overdueTypeName: null,
          remark: null
        },
        assignRuleDetailList: [
          {
            assignRuleCfg: {},
            collectorTagsCfgList: []
          }
        ]
      },
      operateType: 'view', // new 新建规则，view 查看
      closeModalRule: true, // modal确定按钮点击时，是否关闭modal
      collectorConfigList: [], // 催收人员配置
      collectorConfigListTemp: [], // 临时催收人员配置
      columns2: [
        {
          align: 'center',
          title: '催收人员',
          key: 'assignRuleCfg.collectorCode',
          width: 150,
          render: function (h, params) {
            return h('span', {}, params.row.assignRuleCfg.collectorName)
          }
        },
        {
          align: 'center',
          title: '分配比例',
          key: 'assignRuleCfg.assignRatio',
          width: 150,
          render: function (h, params) {
            const vm = this
            return h('Input', {
              props: {
                type: 'text',
                value: vm.collectorConfigListTemp[params.index].assignRuleCfg.assignRatio
              },
              on: {
                'on-change' (e) {
                  let v = e.target.value
                  // 只能输入数字
                  if (!vm.$util.regExpNum.test(v)) {
                    v = 0
                  }
                  /**
                   * 值不变vue不会重新渲染
                   * 所以先将input的值赋值给变量，渲染后再修改变量的值
                   */
                  vm.$set(vm.collectorConfigListTemp[params.index].assignRuleCfg, 'assignRatio', e.target.value)
                  vm.$nextTick(() => {
                    vm.$set(vm.collectorConfigListTemp[params.index].assignRuleCfg, 'assignRatio', v)
                  })
                }
              }
            })
          }.bind(this)
        },
        {
          align: 'center',
          title: '标签',
          key: 'collectorTagsCfgList',
          render: function (h, params) {
            var vm = this
            var tagsList = vm.collectorConfigListTemp[params.index].collectorTagsCfgList
            if (tagsList && tagsList != null && tagsList.length > 0) {
              let ary = tagsList.map(function (item) {
                return item.tagCode
              })
              vm.collectorConfigListTemp[params.index].options = ary
            }
            return h('Select', {
              props: {
                multiple: true,
                'label-in-value': true,
                value: vm.collectorConfigListTemp[params.index].options
              },
              on: {
                'on-change' (options) {
                  vm.collectorConfigListTemp[params.index].collectorTagsCfgList = []
                  for (let i = 0; i < options.length; i++) {
                    let option = options[i]
                    let tag = vm.getOverdueTagByTagCode(option.value)
                    vm.collectorConfigListTemp[params.index].collectorTagsCfgList.push({
                      tagCode: tag.tagCode,
                      tagName: tag.tagName,
                      mappingProperty: tag.mappingProperty,
                      mappingValue: tag.mappingValue
                    })
                  }
                  let aryTagCode = options.map(function (item) {
                    return item.value
                  })
                  // params.row.options = aryTagCode
                  vm.collectorConfigListTemp[params.index].options = aryTagCode
                }
              }
            }, this.selectDataOverdueTags.map(function (item) {
              return h('Option', {props: {value: item.tagCode}}, item.tagName)
            }))
          }.bind(this)
        }
      ]

    }
  },
  methods: {
    changePage (pageIndex) {
      this.pageDataRule.pageNum = pageIndex
      var params = {pageNum: this.pageDataRule.pageNum, pageSize: this.pageDataRule.pageSize}
      this.search(params)
    },
    search (params) {
      var vm = this
      var url = 'debtor/general/rule/service/productOverdueCfgPages/' + params.pageNum + '/' + params.pageSize
      this.$ajax.post(this.$appContext.marvels_core_debtor + url).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        vm.pageDataRule = data.data
      })
    },
    // 获取逾期类型下拉列表
    getOverdueTypes () {
      var vm = this
      var url = 'debtor/general/rule/service/overdueTypeCfgList'
      this.$ajax.post(this.$appContext.marvels_core_debtor + url).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        vm.selectDataOverdueTypes = data.data
      })
    },
    // 获取催收人员
    getCollectors () {
      var vm = this
      var url = 'debtor/general/rule/service/usersByRoleCode'
      var params = {roleCode: 'collector'}
      this.$ajax.get(this.$appContext.marvels_core_debtor + url, {params: params}).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        vm.collectors = data.data
      })
    },
    // 获取逾期标签配置
    getOverdueTags () {
      var vm = this
      var url = 'debtor/general/rule/service/collectorTagsCfgList'
      this.$ajax.post(this.$appContext.marvels_core_debtor + url).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        vm.selectDataOverdueTags = data.data
      })
    },
    // 遍历标签配置列表获取标签
    getOverdueTagByTagCode (tagCode) {
      if (tagCode && tagCode != null && tagCode !== '') {
        for (let i = 0; i < this.selectDataOverdueTags.length; i++) {
          var tag = this.selectDataOverdueTags[i]
          if (tagCode === tag.tagCode) {
            return tag
          }
        }
      }
      return null
    },
    changePattern (option) {
      if (option && option != null) {
        this.ruleConfig.productOverdueCfg.patternCode = option.value
        this.ruleConfig.productOverdueCfg.patternName = option.label
      }
    },
    changeOverdueType (option) {
      if (option && option != null) {
        this.ruleConfig.productOverdueCfg.overdueTypeCode = option.value
        this.ruleConfig.productOverdueCfg.overdueTypeName = option.label
      }
    },
    // 新建规则，初始化催收人员列表
    newRule () {
      this.operateType = 'new'
      this.modalRule = true
      this.initRuleConfig()
      this.collectorConfigList = []
      if (this.collectors != null && this.collectors.length > 0) {
        for (let i = 0; i < this.collectors.length; i++) {
          let collector = this.collectors[i]
          let data = {assignRuleCfg: {collectorCode: collector.userCode, collectorName: collector.userNamep, assignRatio: 0}, collectorTagsCfgList: []}
          this.collectorConfigList.push(data)
        }
      }
      this.collectorConfigListTemp = this.$util.cloneObject(this.collectorConfigList)
    },
    handleOk () {
      this.closeModalRule = false
      var isOk = this.handleOkValid()
      if (!isOk) {
        // this.closeModalRule = isOk
        return
      }
      this.collectorConfigList = this.$util.cloneObject(this.collectorConfigListTemp)
      this.ruleConfig.assignRuleDetailList = this.$util.cloneObject(this.collectorConfigList)
      var params = this.ruleConfig
      var url = 'debtor/general/rule/service/saveNewAutoAssignRule'
      var vm = this
      this.$ajax.post(this.$appContext.marvels_core_debtor + url, params).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        this.closeModalRule = true
        this.modalRule = false
        this.$Message.success(message)
        vm.changePage(1)
      })
    },
    handleOkValid () {
      var isOk = true
      if (this.collectorConfigListTemp == null || this.collectorConfigListTemp.length < 1) {
        this.$Message.warning('请先配置催收岗人员')
        isOk = false
        return isOk
      }
      if (this.ruleConfig.productOverdueCfg.patternCode == null || this.ruleConfig.productOverdueCfg.patternCode === '' ||
          this.ruleConfig.productOverdueCfg.overdueTypeCode == null || this.ruleConfig.productOverdueCfg.overdueTypeCode === '') {
        this.$Message.warning('产品类型和逾期类型不能为空')
        isOk = false
        return isOk
      }
      for (let i = 0; i < this.collectorConfigListTemp.length; i++) {
        let assignRuleCfg = this.collectorConfigListTemp[i].assignRuleCfg
        if (assignRuleCfg.assignRatio === undefined || assignRuleCfg.assignRatio == null || assignRuleCfg.assignRatio === '') {
          this.$Message.warning('分配比例不能为空')
          isOk = false
          return isOk
        }
      }
      var totalAssignRatio = 0
      for (let i = 0; i < this.collectorConfigListTemp.length; i++) {
        let assignRuleCfg = this.collectorConfigListTemp[i].assignRuleCfg
        totalAssignRatio += parseInt(assignRuleCfg.assignRatio)
      }
      if (totalAssignRatio !== 100) {
        this.$Message.warning('分配比例合计必须等于100')
        isOk = false
        return isOk
      }
      return isOk
    },
    // 判断closeModalRule的状态来控制modal是否关闭
    modalRuleVisibleChange (v) {
      if (!this.closeModalRule) {
        this.modalRule = true
      }
    },
    handleCancel () {
      this.closeModalRule = true
    },
    // 查看规则配置详情
    showRuleConfigDetail (id) {
      var vm = this
      var url = 'debtor/general/rule/service/autoAssignRuleDetailById'
      var params = {id: id}
      this.$ajax.get(this.$appContext.marvels_core_debtor + url, {params: params}).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        vm.operateType = 'view'
        vm.modalRule = true
        vm.ruleConfig = data.data
        vm.collectorConfigList = vm.ruleConfig.assignRuleDetailList
        vm.collectorConfigListTemp = vm.$util.cloneObject(vm.collectorConfigList)
      })
    },
    // 生效，失效规则
    updateConfigValid (rowData, validFlag) {
      var url = 'debtor/general/rule/service/updateConfigValid'
      var params = {id: rowData.id, validFlag: validFlag, patternCode: rowData.patternCode, overdueTypeCode: rowData.overdueTypeCode}
      this.$ajax.post(this.$appContext.marvels_core_debtor + url, params).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          this.$Message.warning(message)
          return
        }
        this.$Message.success(message)
        rowData.validFlag = validFlag
        vm.changePage(1)
      })
    },
    init () {
      var params = {pageNum: this.pageDataRule.pageNum, pageSize: this.pageDataRule.pageSize}
      this.search(params)
      this.getOverdueTypes()
      this.getCollectors()
      this.getOverdueTags()
    },
    // 复制新建规则数据结构给新建规则的规则配置
    initRuleConfig () {
      this.ruleConfig = this.$util.cloneObject(this.newRuleConfigTempData)
    }
  },
  computed: {

  },
  mounted () {
    this.$ajax = this.$util.ajax()
    this.baseUrl = this.$appContext.marvels_core_debtor
    this.init()
  },
  created () {
    this.initRuleConfig()
  }
}
</script>
